package com.cat.dataStructure02;

import java.util.*;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/power-grid-maintenance/
 * @create 2025/10/31 15:09
 * @since JDK17
 */

class Solution86 {
    List<Integer>[] g;
    int[] belong;

    public int[] processQueries(int c, int[][] connections, int[][] queries) {
        g = new ArrayList[c + 1];
        Arrays.setAll(g, i -> new ArrayList<>());
        for (var cs : connections) {
            g[cs[0]].add(cs[1]);
            g[cs[1]].add(cs[0]);
        }

        belong = new int[c + 1];
        List<PriorityQueue<Integer>> heaps = new ArrayList<>();
        for (int i = 1; i <= c; i++) {
            if (belong[i] > 0) {
                continue;
            }
            var t = new PriorityQueue<Integer>();
            dfs(i, heaps.size(), t);
            heaps.add(t);
        }
        int n = queries.length, i = 0;
        int[] ans = new int[n];
        boolean[] h = new boolean[c + 1];
        for (var q : queries) {
            int x = q[1];
            if (q[0] == 2) {
                h[x] = true; // 已经离线
                continue;
            }
            if (!h[x]) {
                ans[i++] = x;
                continue;
            }
            var pq = heaps.get(belong[x]);
            while (!pq.isEmpty() && h[pq.peek()]) {
                pq.poll();
            }
            ans[i++] = pq.isEmpty() ? -1 : pq.peek();
        }
        return Arrays.copyOf(ans, i);
    }

    void dfs(int x, int f, PriorityQueue<Integer> pq) {
        belong[x] = f;
        pq.add(x);
        for (int y : g[x]) {
            if (belong[y] < 0) {
                dfs(y, f, pq);
            }
        }
    }
}